package com.scau.hwadee.examination.utils;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author: YHX
 * @Date: 2019/7/4 14:08
 * 用来返回本机ipv4地址的工具类
 */
public class LocalUtils {
    public static String getLocalHost() throws Exception{
        Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
        InetAddress ipv6Address = null;

        while (enumeration.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) enumeration.nextElement();
            Enumeration en = networkInterface.getInetAddresses();

            while (en.hasMoreElements()) {
                InetAddress address = (InetAddress) en.nextElement();
                if (!address.isLoopbackAddress()) {
                    if (!(address instanceof Inet6Address)) {
                        return normalizeHostAddress(address);
                    }

                    ipv6Address = address;
                }
            }
        }
        if (ipv6Address != null) {
            return normalizeHostAddress(ipv6Address);
        } else {
            InetAddress localHost = InetAddress.getLocalHost();
            return normalizeHostAddress(localHost);
        }
    }
    public static String normalizeHostAddress(InetAddress localHost) {
        return localHost instanceof Inet6Address ? "[" + localHost.getHostAddress() + "]" : localHost.getHostAddress();
    }
}
